<?php
/**
 * Created by PhpStorm.
 * User: LENOVO
 * Date: 2019/3/21
 * Time: 23:36
 */

namespace app\admin\controller;


use common\Ret;
use controller\AuthBasic;
use service\AuthService;
use service\DataService;
use service\QueryService;
use think\Db;
use think\Log;

class Auth extends AuthBasic{
    public $title = "权限管理";
    public $table = "SysAuth";
    public function _index_where_filter(&$query, $where) {
        if(session("user.username") !== config('admin')) {
            $query->where('adduser', session("user.id"));
        }
        $filter = [
            "like" => ['name', 'remark'],
            "=" => ['status']
        ];
        QueryService::decorateQuery($query, $where, $filter);
    }
    public function index() {
        return $this->_list($this->table, input(''));
    }
    public function add() {
        return $this->_form($this->table, 'form');
    }
    public function edit() {
        return $this->_form($this->table, 'form');
    }

    public function auth() {
        if(!$this->request->isPost()) {
            $id = input('id');
            $nodes = session("user.nodes");
            $menu_ids = Db::name("SysAuthRecord")->where("auth_id", $id)->column("menu_id");
            $auth = Db::name("SysAuth")->where("id", $id)->find();
            $this->assign("auth", $auth);
            $this->assign("nodes", AuthService::sortNode($nodes));
            $this->assign("node_ids", $menu_ids);
            return $this->fetch();
        }
        $auths = input('nodes/a',[]);
        $id = input('id');
        Db::startTrans();
        try{
            Db::name("SysAuthRecord")->where("auth_id", $id)->delete();
            $auth_records = [];
            foreach ($auths as $auth) {
                array_push($auth_records, [
                   "auth_id"    => $id,
                   "menu_id"    => $auth
                ]);
            }
            Db::name("SysAuthRecord")->insertAll($auth_records);
            Db::commit();
            return $this->ret->setCode(Ret::$_RET_RELOAD)->setMsg("授权成功")->toJson();
        }catch(\Exception $e) {
            Db::rollback();
            Log::write($e->getMessage());
            return $this->ret->setMsg(Ret::$_RET_ERROR)->setMsg("系统发生错误，错误:{$e->getMessage()}")->toJson();
        }
    }
    public function del() {
        if (DataService::update($this->table)) {
            return $this->ret->setCode(Ret::$_RET_RELOAD)->setMsg('删除成功')->toJson();
        }
        return $this->ret->setCode(Ret::$_RET_ERROR)->setMsg('删除失败，请重试')->toJson();
    }
    public function forbid() {
        if (DataService::update($this->table)) {
            return $this->ret->setCode(Ret::$_RET_RELOAD)->setMsg('操作成功')->toJson();
        }
        return $this->ret->setCode(Ret::$_RET_ERROR)->setMsg('操作失败，请重试')->toJson();
    }
}